var waybillList = {};
var WaybillList = function () {
    this.dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
    this.aStationText = "发出站";
    this.arriveStationText = "到站";
    //初始化信息
    this.init = function () {
        var businessTypes = "YWLX_T";
        var paramMap = layuiFunciton.getURLParamMap();
        if (paramMap) {
            $("#tranType").val(paramMap["tranType"]);
            if (paramMap["tranType"] == "1") {//铁路运输
                businessTypes = "YWLX_T";
                //发出站
                waybillList.initSelect("aStation", "ZD");
                //到站
                waybillList.initSelect("arriveStation", "ZD");
            } else if (paramMap["tranType"] == "2") {//水路运输
                businessTypes = "YWLX_S";
                $("#goodsWere").text("提单号");
                $("#aStationText").text("发出港");
                $("#arriveStationText").text("到港");
                waybillList.aStationText = "发出港";
                waybillList.arriveStationText = "到港";
                //发出港
                waybillList.initSelect("aStation", "GK");
                //到港
                waybillList.initSelect("arriveStation", "GK");
            } else if (paramMap["tranType"] == "3") {//公路运输

                this.arriveStationText = "卸货地点";
                //发出站
                waybillList.initSelect("aStation", "ZD");
                //到站
                waybillList.initSelect("arriveStation", "ZD");
                businessTypes = "YWLX_G";
            }
        }
        $("#orderDate").val(waybillList.getCurrentMonthFirst() + ' ~ ' + waybillList.getCurrentMonthLast());

        //初始化下单日期开始时间
        layuiFunciton.layTime({
            elem: '#startDate'
            , format: 'yyyy-MM-dd'
            ,value: waybillList.getCurrentMonthFirst()
        });
        //初始化下单日期结束时间
        layuiFunciton.layTime({
            elem: '#endDate'
            , format: 'yyyy-MM-dd'
            ,value: waybillList.getCurrentMonthLast()
        });

        //初始化发运日期开始时间
        layuiFunciton.layTime({
            elem: '#startDate1'
            , format: 'yyyy-MM-dd'
        });
        //初始化发运日期结束时间
        layuiFunciton.layTime({
            elem: '#endDate1'
            , format: 'yyyy-MM-dd'
        });
        //初始化搜索条件业务员
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sysUser/findUserList',
            data: {page: 1, limit: 99999},
            maskState: false,         //是否开启遮罩
            success: function (data) {
                var optionHtml = '<option value="">请选择</option>';
                data.forEach(function (obj, index) {
                    optionHtml += '<option value="' + obj.name + '">' + obj.name + '</option>';
                });
                $("#salesman").html(optionHtml);
            }
        });
        //初始化数据字典
        //业务类型
        waybillList.initSelect("businessTypes", businessTypes);
        //品名
        waybillList.initSelect("ofTheGoods", "Of_the_goods");
        //箱型
        waybillList.initSelect("aBox", "XX");
        //发货单位
        waybillList.initSelect("deliveryUnit", "FHDW");
        //收货人
        //waybillList.initSelect("receivingUnit", "SHDW");
        //结算人
        waybillList.initSelect("settlementPeople", "JSR");
        //装货地点
        waybillList.initSelect("standby1", "ZHDD");
    };
    //初始化表格
    this.initTalbe = function () {
        var paramMap = layuiFunciton.getURLParamMap();
        layuiFunciton.tableInit({
            toolbar: '.btn',
            tableId: 'waybillListTableId',
            url: layuiFunciton.URL + '/wb/shipping/order/selectPage?states=-2',
            id: 'waybillListId',
            searchFromId: 'searchForm',
            totalRow: true,
            tableFilter: 'waybillListFilter',  //表格监听名称,
            cols: [[
                {type: 'numbers', title: '序号', fixed: 'left'},
                {field: 'orderCode', width: 150, title: '订单编号', sort: true},
                {field: 'salesman', width: 100, title: '业务员', sort: true, totalRowText: '合计：'}
                , {field: 'orderDate', width: 120, title: '下单日期', sort: true}
                , {field: 'dateShipment', width: 120, title: '发运日期', sort: true}
                , {
                    field: 'businessTypes', title: '业务类型', sort: true,
                    templet: function (row) {
                        if (waybillList.dictMap[row.businessTypes]) {
                            return waybillList.dictMap[row.businessTypes];
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    field: 'ofTheGoods', title: '品名', sort: true,
                    templet: function (row) {
                        if (waybillList.dictMap[row.ofTheGoods]) {
                            return waybillList.dictMap[row.ofTheGoods];
                        } else {
                            return "";
                        }

                    }
                }
                , {
                    field: 'aBox', title: '箱型', sort: true,
                    templet: function (row) {
                        if (waybillList.dictMap[row.aBox]) {
                            return waybillList.dictMap[row.aBox];
                        } else {
                            return "";
                        }
                    }
                }
                , {field: 'cartonNo', title: '箱号', sort: true}
                , {
                    field: 'deliveryUnit', title: '发货单位', sort: true,
                    templet: function (row) {
                        if (waybillList.dictMap[row.deliveryUnit]) {
                            return waybillList.dictMap[row.deliveryUnit];
                        } else {
                            return "";
                        }
                    }
                }, {
                    field: 'standby1', title: '装货地点', sort: true,
                    templet: function (row) {
                        if (waybillList.dictMap[row.standby1]) {
                            return waybillList.dictMap[row.standby1];
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    field: 'aStation', title: waybillList.aStationText, sort: true,hide: (paramMap["tranType"] == "3"),
                    templet: function (row) {
                        if (waybillList.dictMap[row.aStation]) {
                            return waybillList.dictMap[row.aStation];
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    field: 'arriveStation', title: waybillList.arriveStationText, sort: true,
                    templet: function (row) {
                        if (waybillList.dictMap[row.arriveStation]) {
                            return waybillList.dictMap[row.arriveStation];
                        } else {
                            return "";
                        }
                    }
                }, {
                    field: 'arriveStation', title: '到站承运', sort: true, hide: paramMap["tranType"] != "1",
                    templet: function (row) {
                        if (waybillList.dictMap[row.standby3]) {
                            return waybillList.dictMap[row.standby3];
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    field: 'receivingUnit', title: '收货人', sort: true/*,
                     templet: function (row) {
                     if (waybillList.dictMap[row.receivingUnit]) {
                     return waybillList.dictMap[row.receivingUnit];
                     } else {
                     return "";
                     }
                     }*/
                }
                , {
                    field: 'settlementPeople', title: '结算人', sort: true,
                    templet: function (row) {
                        if (waybillList.dictMap[row.settlementPeople]) {
                            return waybillList.dictMap[row.settlementPeople];
                        } else {
                            return "";
                        }
                    }
                }, {
                    field: 'standby', align: "center", title: '已开发票', sort: true,
                    templet: function (row) {
                        if (row.standby == 1) {
                            return "<input type='checkbox' lay-skin='primary'  disabled checked/>";
                        } else {
                            return "<input type='checkbox' lay-skin='primary' disabled />";
                        }
                    }
                }
                , {field: 'goodsWere', title: '货票号', sort: true}
                , {field: 'chargeableWeight', title: '计费重量', sort: true}
                , {
                    field: 'accountsReceivableAmount', title: '应收金额', sort: true,
                    totalRowText: '<span style="color: green" class="accountsReceivableAmount">0.00</span>',
                    templet: function (row) {
                        return Number(row.accountsReceivableAmount).toFixed(2);
                    }
                }
                , {
                    field: 'totalCosts', title: '费用总额', sort: true,
                    totalRowText: '<span style="color: green" class="totalCosts">0.00</span>',
                    templet: function (row) {
                        return Number(row.totalCosts).toFixed(2);
                    }
                }
                , {
                    field: 'states', title: '状态', sort: true,
                    templet: function (row) {
                        if (row.states == 0) {
                            return "已下单";
                        } else if (row.states == 1) {
                            return '<span style="color: #ffd80f">已发运</span>';
                        } else if (row.states == 2) {
                            if(row.sterilisationAmount){
                                return "收款￥ "+row.sterilisationAmount;
                            }else{
                                return '<span style="color: red">待收款</span>';
                            }
                        } else if (row.states == 3) {
                            return '<span style="color: #009feb">已收款</span>';
                        } else {
                            return "";
                        }
                    }
                }
                , {
                    title: '操作',
                    width: 200,
                    align: "center",
                    templet: '#voucherBar',
                    fixed: 'right',
                    templet: function (row) {
                        var returnHtml = "";
                        if (row.states == 0) {
                            returnHtml = '<a href="javascript:void(0)" style="color:#009feb" lay-event="confirm">确认</a>';
                        } else if (row.states == 2) {
                            returnHtml = '<a href="javascript:void(0)" style="color:#009feb;" lay-event="details">详情</a><a href="javascript:void(0)" style="color:#009feb;padding-left: 8px;" lay-event="cancelConfirm">取消确认</a>';
                        } else if (row.states == 3) {
                            returnHtml = '<a href="javascript:void(0)" style="color:#009feb;" lay-event="details">详情</a><a href="javascript:void(0)" style="color:#009feb;padding-left: 8px;" lay-event="supplement">增补</a>';
                        }
                        if (row.states > 0) {
                            if (row.standby == 1) {//是否已开发票
                                returnHtml += '<a href="javascript:void(0)" style="color:#009feb;padding-left: 8px;" lay-event="cancelMakeOutInvoice">取消开票</a>';
                            } else {
                                returnHtml += '<a href="javascript:void(0)" style="color:#009feb;padding-left: 8px;" lay-event="makeOutInvoice">开票</a>';
                            }
                        }
                        return returnHtml;
                    }
                }
            ]],
            returnData: function (res) {
                var accountsReceivableAmount = 0.00, totalCosts = 0.00;
                res.forEach(function (obj, index) {
                    accountsReceivableAmount = (Number(accountsReceivableAmount) + Number(obj.accountsReceivableAmount)).toFixed(2);
                    totalCosts = (Number(totalCosts) + Number(obj.totalCosts)).toFixed(2);
                });
                $(".accountsReceivableAmount").html(accountsReceivableAmount);
                $(".totalCosts").html(totalCosts);
            },
            tools: {
                //双击
                rowDouble:function (row) {
                    if (row.states == 0) {
                        layuiFunciton.layerOpen({
                            title: "确认",
                            finder: "form",
                            content: "confirm.html",
                            data: row,
                            end: function () {
                                layuiFunciton.refresh('searchForm', 'waybillListId');
                            }
                        });
                    }
                },
                //确认
                confirm: function (row) {
                    layuiFunciton.layerOpen({
                        title: "确认",
                        finder: "form",
                        content: "confirm.html",
                        data: row,
                        end: function () {
                            layuiFunciton.refresh('searchForm', 'waybillListId');
                        }
                    });
                },
                makeOutInvoice: function (row) {
                    layuiFunciton.layerOpen({
                        title: "开票信息",
                        finder: "form",
                        content: "edit.html",
                        data: row,
                        end: function () {
                            layuiFunciton.refresh('searchForm', 'waybillListId');
                        }
                    });
                },
                //详情
                details: function (row) {
                    layuiFunciton.layerOpen({
                        title: "详情",
                        finder: "form",
                        content: "details.html",
                        data: row,
                        end: function () {
                            layuiFunciton.refresh('searchForm', 'waybillListId');
                        }
                    });
                }
                //增补
                , supplement: function (row) {
                    layuiFunciton.layerOpen({
                        title: "增补",
                        finder: "form",
                        content: "supplement.html",
                        data: row,
                        end: function () {
                            layuiFunciton.refresh('searchForm', 'waybillListId');
                        }
                    });
                }//取消确认
                , cancelConfirm: function (row) {
                    layuiFunciton.alert({
                        types: 'confirm', title: '是否取消确认？', success: function () {
                            layuiFunciton.ajaxRequest({
                                url: layuiFunciton.URL + '/wb/shipping/order/updateWbShippingOrder',
                                method: 'post',
                                data: {id: row.id, states: 0},
                                success: function (data) {
                                    if (data > 0) {
                                        layuiFunciton.success('操作成功！', function () {
                                            layuiFunciton.refresh('searchForm', 'waybillListId');
                                        })
                                    } else if (data == -1) {
                                        layuiFunciton.warn('已核销无法取消确认！', function () {
                                            layuiFunciton.refresh('searchForm', 'waybillListId');
                                        })
                                    } else {
                                        layuiFunciton.warn('未知错误！', function () {
                                            layuiFunciton.refresh('searchForm', 'waybillListId');
                                        })
                                    }
                                }
                            });
                        }
                    });
                },
                //取消开票
                cancelMakeOutInvoice: function (row) {
                    layuiFunciton.alert({
                        types: 'confirm', title: '取消开票将清空开票信息，确认继续？', success: function () {
                            layuiFunciton.ajaxRequest({
                                url: layuiFunciton.URL + '/wb/shipping/order/updateWbShippingOrder',
                                method: 'post',
                                data: {
                                    id: row.id,
                                    standby: 0,
                                    invoiceCode: "",
                                    invoiceNo: ""
                                },
                                success: function (data) {
                                    if (data > 0) {
                                        layuiFunciton.success('操作成功！', function () {
                                            layuiFunciton.refresh('searchForm', 'waybillListId');
                                        })
                                    } else if (data == -1) {
                                        layuiFunciton.warn('“未开票”状态无需取消开票！', function () {
                                            layuiFunciton.refresh('searchForm', 'waybillListId');
                                        })
                                    } else {
                                        layuiFunciton.warn('未知错误！', function () {
                                            layuiFunciton.refresh('searchForm', 'waybillListId');
                                        })
                                    }
                                }
                            })
                            ;
                        }
                    });
                },
                export: function () {
                    location.href = layuiFunciton.URL + '/wb/shipping/order/wayBillExport?states=-2&' + $("#searchForm").serialize();
                }
            }
        });
    };
    //获取当月第一天
    this.getCurrentMonthFirst = function () {
        var date = new Date();
        date.setDate(1);
        return waybillList.dateFtt("yyyy-MM-dd", date);
    };
    //获取当月最后一天
    this.getCurrentMonthLast = function () {
        var date = new Date();
        var currentMonth = date.getMonth();
        var nextMonth = ++currentMonth;
        var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
        var oneDay = 1000 * 60 * 60 * 24;
        return waybillList.dateFtt("yyyy-MM-dd", new Date(nextMonthFirstDay - oneDay));
    };
    //时间格式化
    this.dateFtt = function (fmt, date) {
        var o = {
            "M+": date.getMonth() + 1,     //月份
            "d+": date.getDate(),     //日
            "h+": date.getHours(),     //小时
            "m+": date.getMinutes(),     //分
            "s+": date.getSeconds(),     //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds()    //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    this.event = function () {
        $("#search").click(function () {
            if($("#startDate").val().length == 0 || $("#endDate").val().length == 0){
                if(!($("#startDate").val().length == 0 && $("#endDate").val().length == 0)){
                    layuiFunciton.warn('下单日期开始时间和结束时间必填！');
                    return;
                }
            }
            if($("#startDate1").val().length == 0 || $("#endDate1").val().length == 0){
                if(!($("#startDate1").val().length == 0 && $("#endDate1").val().length == 0)){
                    layuiFunciton.warn('发运日期开始时间和结束时间必填！');
                    return;
                }
            }
            if($('#startDate').val() && $('#endDate').val()){
                $("#orderDate").val($('#startDate').val() + ' ~ ' + $('#endDate').val());
            }else{
                $('#startDate').val("");
                $('#endDate').val("");
                $("#orderDate").val("");
            }
            if($('#startDate1').val() && $('#endDate1').val()){
                $("#dateShipment").val($('#startDate1').val() + ' ~ ' + $('#endDate1').val());
            }else{
                $('#startDate1').val("");
                $('#endDate1').val("");
                $("#dateShipment").val("");
            }
            layuiFunciton.refresh('searchForm', 'waybillListId');
        });
    };
    //初始化input 搜索
    this.initSelect = function (item,typeCode) {
        $("#"+item).attr("readonly","");
        //引入自定义插件
        layui.config({
            base: '/public/plugin/tableSelect/' //设置自定义插件路径:根据实际路径进行设置
        }).use(['tableSelect'], function() {
            var tableSelect = layui.tableSelect;
            tableSelect.render({
                elem: '#'+item,	//定义输入框input对象
                checkedKey: 'valCode', //表格的唯一建值，非常重要，影响到选中状态 必填
                searchKey: 'valName',	//搜索输入框的name值 默认keyword
                searchPlaceholder: '关键词搜索',	//搜索输入框的提示文字 默认关键词搜索
                table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                    url:layuiFunciton.URL + '/sys/dictVal/getByTypeCode?typeCode='+typeCode,
                    page:false,
                    cols: [[
                        {field: 'valName', title: '请选择（双击）',align: "center"}
                    ]]
                },
                done: function (elem, data) {
                    $('#'+item).val(data.data[0].valName);
                    $('#'+item).siblings("input[type='hidden']").val(data.data[0].valCode);
                }
            });
            var dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
            if($('#'+item).val()){
                $("#" + item).after('<input type="hidden" name="'+item+'" value="'+$('#'+item).val()+'" >');
                $('#'+item).val(dictMap[$('#'+item).val()]);
            }else{
                $("#" + item).after('<input type="hidden" name="'+item+'" value="" >');
            }
        });
    }
};
waybillList = new WaybillList();
waybillList.init();
waybillList.initTalbe();
waybillList.event();